<?php
namespace backend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;


class Posts extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    const STATUS = 1;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%posts}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'describe','admin_id','admin_name'], 'trim'],
            [['title','admin_id','admin_name'], 'required','message' => '{attribute}不能为空'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'title' => '标题',
            'describe' => '内容',
            'admin_id' => '发帖人id',
            'admin_name' => '发帖人',
        ];
    }

    public function scenarios()
    {
        return [
            'default' => [
                'title',
                'describe',
                'sort',
                'banner',
                'video',
            ],
            'create' => [
                'id',
                'title',
                'describe',
                'img',
                'admin_id',
                'admin_name'.
                'status',
                'create_time',
                'update_time',
                'deleted_at',
            ],
            'update' => [
                '!id',
                'title',
                'describe',
                'img',
                'sort',
                'banner',
                'video',
                'admin_id',
                'admin_name'.
                'status',
                'create_time',
                'update_time',
                'deleted_at',
            ],
        ];
    }

    public static function saveData($id,$params){
        $model = static::findOne(['id' => $id]);
        if(empty($model)){
            return false;
        }
        $model->status = $params['status'];
        if($params['status'] == 2){
            $model->error = $params['error'];
        }
//        $model->save();
//        var_dump($model->getErrors());die;
        return $model->save();
    }

    public static function deleteData($id){
        $model = static::findOne(['id' => $id]);
        if(empty($model)){
            return true;
        }
        $model->deleted_at = time();
        return $model->save();
    }

    /**
     * 更新数据
     * @author hey_heyang(635870453@qq.com)
     */
    public static function saveInfo($scenario, $data, $id = 0){
        if (!in_array($scenario, ['create', 'update'])) {
            return false;
        }
        $t = static::getDb()->beginTransaction();
        try {
            if ($scenario == 'update') {
                $id = intval($id);
                if (!$id) {
                    return false;
                }
                $model           = static::findOne(['id' =>$id]);
                if(empty($model)) throw new Exception('不存在此用户');
                $model->scenario = 'update';
            } else {
                $model           = new self();
                $model->scenario = 'create';
            }
            $model->setAttributes($data, false);
            if (!$model->save()) {
                $t->rollBack();
                return $model;
            }
            $model->refresh();
            $t->commit();
            return $model->attributes['id'];
            //return $model;
        } catch (Exception $e) {
            $t->rollback();
            return $e;
        }
    }

    /**
     * @inheritdoc
     */
    public static function selectFieldData($field)
    {
        $query = new \yii\db\Query();
        $query->select($field)->from('posts');
        $query->where(['deleted_at' => null]);
        $query->andWhere(['status' => 3]);
        $query->orderBy([
            'created_at' => SORT_DESC,
        ]);

        $command = $query->createCommand();
        $result = $command->queryAll();
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function selectInfo($data = [])
    {
        $query = new \yii\db\Query();
        $query->select(['*'])->from('posts');
        $query->where(['deleted_at' => null]);
        $query->orderBy([
            'created_at' => SORT_DESC,
        ]);
        if(!empty($data['status'])){
            $query->andWhere(['status' => $data['status']]);
        }
        if(!empty($data['start_date']) && !empty($data['end_date'])){
            $query->andFilterWhere(['between','created_at',$data['start_date'], $data['end_date']]);
        }
        $command = $query->createCommand();
        $result = $command->queryAll();
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function selectData($data = [])
    {
        $query = new \yii\db\Query();
        $group = new \backend\models\Group();
        $item = new \backend\models\NewProject();
        $movie = new \backend\models\MovieCollege();
        $collect = new \backend\models\PostsCollect();
        $query->select(['`posts`.`*`,`j`.`item_id`,`j`.`group_id`,`j`.`movie_id`'])->from('posts');
        $query->leftJoin('posts_join j','`posts`.`id` = `j`.`posts_id`');
        $query->leftJoin('member m','`posts`.`set_posts_id` = `m`.`id`');
        $query->where(['posts.deleted_at' => null]);
        $query->orderBy([
            'posts.created_at' => SORT_DESC,
        ]);
        if(!empty($data['title'])){
            $query->andWhere(['like', 'title', $data['title']]);
        }
        if(!empty($data['set_posts_name'])){
            $query->andWhere(['like', '`m`.`username`', $data['set_posts_name']]);
        }
        if(!empty($data['movie_id'])){
            $query->andWhere(['movie_id' => $data['movie_id']]);
        }
        if(!empty($data['item_id'])){
            $query->andWhere(['item_id' => $data['item_id']]);
        }
        if(!empty($data['group_id'])){
            $query->andWhere(['group_id' => $data['group_id']]);
        }
        if(!empty($data['status'])){
            $query->andWhere(['posts.status' => $data['status']]);
        }
        $command = $query->createCommand();
        $result = $command->queryAll();
        foreach ($result as $k => $v){
            $groupInfo = $group::findOneDataField($v['group_id'],['`id`,`name`']);
            $movieInfo = $movie::findOneDataField($v['movie_id'],['`id`,`title`']);
            $itemInfo = $item::findOneData($v['item_id'],['`id`,`title`']);
            $collectNum = $collect::selectData('`id`',$v['id'],['is_collect' => 1]);
            $likeNum = $collect::selectData('`id`',$v['id'],['is_like' => 1]);
            $result[$k]['item_id'] = empty($itemInfo['id'])?'':$itemInfo['id'];
            $result[$k]['item'] = empty($itemInfo['title'])?'':$itemInfo['title'];
            $result[$k]['group_id'] = empty($groupInfo['id'])?'':$groupInfo['id'];
            $result[$k]['group'] = empty($groupInfo['name'])?'':$groupInfo['name'];
            $result[$k]['movie_id'] = empty($movieInfo['id'])?'':$movieInfo['id'];
            $result[$k]['movie'] = empty($movieInfo['title'])?'':$movieInfo['title'];
            $result[$k]['collect_num'] = count($collectNum);
            $result[$k]['like_num'] = count($likeNum);
        }
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function findAllData($data,$page = 1,$pageSize = 10)
    {
        $query = new \yii\db\Query();
        $group = new \backend\models\Group();
        $movie = new \backend\models\MovieCollege();
        $query->select(['`posts`.`*`,`j`.`item_id`,`j`.`group_id`,`j`.`movie_id`'])->from('posts');
        $query->leftJoin('posts_join j','`posts`.`id` = `j`.`posts_id`');
        $query->where(['posts.deleted_at' => null]);
        $query->andWhere(['posts.status' => self::STATUS]);
        $query->orderBy([
            'created_at' => SORT_DESC,
        ]);
        if(!empty($data['title'])){
            $query->andWhere(['like', 'title', $data['title']]);
        }
        if(!empty($data['admin_name'])){
            $query->andWhere(['like', 'admin_name', $data['admin_name']]);
        }
        if(!empty($data['item_id'])){
            $query->andWhere(['item_id' => $data['item_id']]);
        }
        if(!empty($data['group_id'])){
            $query->andWhere(['group_id' => $data['group_id']]);
        }
        $page = $page ? $page : 1;
        $pageSize = $pageSize ? $pageSize : 10;
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $command = $query->createCommand();
        $result = $command->queryAll();
        foreach ($result as $k => $v){
            $groupInfo = $group::findOneDataField($v['group_id'],['`id`,`name`']);
            if(empty($groupInfo)){
                $groupInfo = null;
            }
            $movieInfo = $movie::findOneDataField($v['movie_id'],['`id`,`title`']);
            if(empty($movieInfo)){
                $movieInfo = null;
            }
            $result[$k]['group'] = $groupInfo;
            $result[$k]['movie'] = $movieInfo;
        }
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function findOneData($id)
    {
        $query = new \yii\db\Query();
        $member = new \backend\models\Member();
        $group = new \backend\models\Group();
        $item = new \backend\models\NewProject();
        $movie = new \backend\models\MovieCollege();
        $query->select(['`posts`.`*`,`j`.`item_id`,`j`.`group_id`,`j`.`movie_id`'])->from('posts');
        $query->leftJoin('posts_join j','`posts`.`id` = `j`.`posts_id`');
        $query->where(['posts.deleted_at' => null]);
        //$query->andWhere(['posts.status' => self::STATUS]);
        $query->andWhere(['posts.id' => $id]);

        $command = $query->createCommand();
        $result = $command->queryOne();
        $groupInfo = $group::findOneDataField($result['group_id'], ['`id`,`name`']);
        $movieInfo = $movie::findOneDataField($result['movie_id'], ['`id`,`title`']);
        $itemInfo = $item::findOneData($result['item_id'],['`id`,`title`']);
        $memberInfo = $member::findOne(['id' => $result['set_posts_id']]);
        $result['group'] = empty($groupInfo)?'':$groupInfo;
        $result['movie'] = empty($movieInfo)?'':$movieInfo;
        $result['item'] = empty($itemInfo)?'':$itemInfo;
        $result['set_posts_name'] = empty($memberInfo['username'])?'':$memberInfo['username'];
        $result['member_name'] = $result['set_posts_name'].'/'.$result['set_posts_id'];
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS]);
    }

    /**
     * @inheritdoc
     */
    public static function findDataByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}
